{% load staticfiles %}
<div class="modal fade" id="data_modal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close"
                        data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    选择统计数据
                </h4>
            </div>

            <div class="modal-body">
                <div class="row">
                    <ul id="myTab" class="nav nav-tabs">
                        <li class="active"><a href="#upload-data" data-toggle="tab">本地数据</a></li>
                        <li><a href="#online-data" data-toggle="tab">在线数据</a></li>
                    </ul>
                    <div id="myTabContent" class="tab-content" style="padding: 5px">
                        <div class="tab-pane fade in active" id="upload-data">
                            <div class="row">
                                <div class="col-md-3">
                                    <label for="id_header" class="control-label">表头：</label>
                                    <select class="form-control" id="id_header">
                                        <option value="1">包含</option>
                                        <option value="2">不包含</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="id_split" class="control-label">分隔字符：</label>
                                    <input type="text" placeholder="默认为," class="form-control" name="description" id="id_split">
                                </div>
                                <div class="col-md-6">
                                    <label for="file-upload" class="control-label">文件</label>
                                    <input type="file" id="file-upload" class="form-control"
                                           onchange="fileUpload(this.files)">
                                </div>
                            </div>
                        </div>
                        <div class="tab-pane fade" id="online-data">
                            <div class="row">
                                <div class="col-md-6">
                                    <label for="id_group" class="control-label">所属图集：</label>
                                    <select name="group" id="id_group" class="form-control" onchange="selectchange()">
                                        {% for group in group_list %}
                                            <option value="{{ group.id }}">{{ group.name }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="id_data" class="control-label">选择数据：</label>
                                    <select name="data" id="id_data" class="form-control">

                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div id="id_info_panel" class="alert alert-success alert-dismissable hide">
                        <button type="button" class="close" id="id_data_panel_close">
                            ×
                        </button>
                        导入成功
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="success()">导入</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    var data_upload = null;
    var is_data_updated = true;
    $("#data_modal").on('shown.bs.modal', function () {
        var groupid = $("#id_group").val();
        var table_select = $("#id_data");
        table_select.html("");
        $.get({% url 'get_tables' %}, {'group_id': groupid}, function (List) {
            List = eval(List);
            if (List.length > 0) {
                for (var i = 0; i < List.length; i++) {
                    var item = '<option value=\"' + List[i].fields.file + '\">' + List[i].fields.name + '</option>';
                    table_select.append(item);
                }
            }
        });
    });
    $("#id_data_panel_close").on("click",function(){
        $("#id_info_panel").addClass("hide");
    });
    function success() {
        if($("#upload-data").hasClass("active"))
        {

        }
        else if($("#online-data").hasClass("active")){
            onlineFileLoad($("#id_data").val().trim());
        }
        $("#btn-carto").addClass("pointer");
        $("#btn-carto").removeClass("disabled");
        $("#btn-carto").attr("data-target", "#carto_modal");
        $("#btn-data-view").removeClass("disabled");
        $("#btn-data-view").removeClass("btn-default");
        $("#btn-data-view").addClass("btn-primary");
    }

    function readData(text, hasheader, spliter) {
        var data = new Array();
        var text_s = text.trim();
        var lines = text_s.split("\n");
        var start = hasheader == true ? 1 : 0;
        var header = null;
        var col_num = 0, row_num = 0;
        if (hasheader == true) {
            header = lines[0].split(spliter);
            header = header.map(function (e) {
                return e.trim()
            });
            row_num = lines.length - 1;
            col_num = header.length;
        }
        else {
            row_num = lines.length;
        }
        for (i = start; i < lines.length; i++) {
            var ss = lines[i].split(spliter);
            if (ss.length <= 1)
                continue;
            var one = new Array();
            for (sss in ss) {
                var trans = parseFloat(ss[sss]);
                if (isNaN(trans))
                    one.push(ss[sss]);
                else
                    one.push(trans);
            }
            data.push(one);
        }
        col_num = data[0].length;
        var content = {
            "hes_header": hasheader,
            "header": header,
            "data": data,
            "row_num": row_num,
            "col_num": col_num,
            "get_attr_index": function (index) {
                return content["data"].map(function (item) {
                    return item[index]
                });
            },
            "get_attr_name": function (name) {
                var index = header.indexOf(name);
                return content["data"].map(function (item) {
                    return item[index]
                });
            },
            "toJSON":function(){
                var data=[];
                for(var i=0;i<content["row_num"];i++)
                {
                    var item={}
                    for(var j=0;j<content["col_num"];j++)
                        item[header[j]]=content["data"][i][j];
                    data.push(item)
                }
                return data;
            },
            "parseJSON":function(JSON){
                content["data"]=[];
                function getIndex(name){
                    return header.indexOf(name);
                }
                for(var i=0;i<JSON.length;i++)
                {
                    var item=[];
                    for(var j in JSON[i]){
                        item[getIndex(j)]=isNaN(parseFloat(JSON[i][j]))?JSON[i][j]:parseFloat(JSON[i][j]);
                    }
                    content["data"].push(item);
                }
            },
            "addAttr":function(array){
                for(var i=0;i<content["data"].length;i++)
                    content["data"][i].push(array[i]);
                content["col_num"]=content["col_num"]+1;
                return true;
            }
        };
        return content;
    }

    function onlineFileLoad(url2)
    {
        var has_header = $("#id_header").val() == "1" ? true : false;
        var spliter = $("#id_split").val()||",";
{#        var media_url="{% url 'media' %}";#}
        Snap.ajax("/media/"+url2,function(e){
            data_upload = readData(e.responseText, has_header, spliter);
            $("#id_info_panel").removeClass("hide");
            is_data_updated=true;
        });
    }
    function fileUpload(f) {
        if (typeof FileReader == 'undefined') {
            alert(message["file_error"]);
        }
        var tempFile = f[0];
        var reader = new FileReader();
        reader.readAsText(tempFile, "GBK");
        var has_header = $("#id_header").val() == "1" ? true : false;
        var spliter = $("#id_split").val()||",";
        reader.onload = function (e) {
            data_upload = readData(e.target.result, has_header, spliter);
            is_data_updated = true;
            $("#id_info_panel").removeClass("hide");
        }
    }

    function selectchange() {
        var groupid = $("#id_group").val();
        var table_select = $("#id_data");
        $.getJSON({% url 'get_tables' %}, {'group_id': groupid}, function (List) {
            List = eval(List);
            table_select.html("");
            if (List.length > 0) {
                for (var i = 0; i < List.length; i++) {
                    var item = '<option value=\"' + List[i].fields.file + '\">' + List[i].fields.name + '</option>';
                    table_select.append(item);
                }
            }
        });
    }
</script>